package com.exject.android.geobasedsoundmanager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.exject.android.geobasedsoundmanager.settings.Settings;
import com.exject.android.geobasedsoundmanager.settings.SettingsImpl;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class ManagerActivity extends MapActivity {

	private static final int E6_MULTIPLY = 1000000;
	private static final int MENU_SETTINGS = 0;
	private static final int MENU_CURRENT_POSITION = 1;

	private Settings settings;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		restoreDefaultSettings();
		initMapView();
	}

	/**
	 * Set the position and zoom level for the
	 */
	private void initMapView() {
		try {
			MapView map = (MapView) this.findViewById(R.id.map);
			map.setBuiltInZoomControls(true);
			MapController mapController = map.getController();

			GeoPoint point = null;
			if (this.settings.isUseStartAddress() == true) {
				point = searchAddress();
			} else {
				point = searchPoint();
			}
			if (point != null) {
				mapController.setCenter(point);
				mapController.setZoom(14);
			} else {
				Toast errorToast = Toast.makeText(this,
						R.string.errorToastNoStartPosition, Toast.LENGTH_SHORT);
				errorToast.show();
			}
		} catch (IOException e) {
			Toast errorToast = Toast.makeText(this,
					R.string.errorToastSearchAddressException,
					Toast.LENGTH_SHORT);
			errorToast.show();
		}
	}

	private GeoPoint searchPoint() {
		return this.settings.getStartPosition();
	}

	private GeoPoint searchAddress() throws IOException {
		Geocoder geocoder = new Geocoder(this);
		GeoPoint point = null;
		Double lat = null;
		Double lon = null;
		List<Address> foundAdresses = geocoder.getFromLocationName(
				this.settings.getStartAddress(), 1);
		for (int i = 0; i < foundAdresses.size(); ++i) {
			Address x = foundAdresses.get(i);
			lat = x.getLatitude();
			lon = x.getLongitude();
		}
		if (lat != null && lon != null) {
			point = new GeoPoint((int) (lat * E6_MULTIPLY), (int) (lon * E6_MULTIPLY));
		} else {
			if (settings.isSettingSet(Settings.CHECK_POSITION_POINT)) {
				Toast errorToast = Toast.makeText(this,
						R.string.errorToastSearchAddressFallback,
						Toast.LENGTH_SHORT);
				errorToast.show();
				point = searchPoint();
			} else {
				Toast errorToast = Toast.makeText(this,
						R.string.errorToastSearchAddress, Toast.LENGTH_SHORT);
				errorToast.show();
			}
		}
		return point;
	}

	/**
	 * Load the default settings from the settings file
	 */
	private void restoreDefaultSettings() {
		this.settings = SettingsImpl.initInstance(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO: CHANGE menu item image
		// TODO: Implement handling (Change default settings)
		menu.add(0, MENU_CURRENT_POSITION, 0, R.string.menuManagerCurrentPosition)
				.setIcon(android.R.drawable.menuitem_background);
		menu.add(0, MENU_SETTINGS, 0, R.string.menuManagerSettings).setIcon(
				android.R.drawable.menuitem_background);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_SETTINGS:
			Intent i = new Intent(this, SettingsActivity.class);
			this.startActivity(i);
			break;
		case MENU_CURRENT_POSITION:
			changeMapPositionToCurrentPosition();
			break;
		}
		return true;
	}

	private void changeMapPositionToCurrentPosition() {
		MapView map = (MapView) this.findViewById(R.id.map);
		map.setBuiltInZoomControls(true);
		MapController mapController = map.getController();
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		
		List<String> providers = locationManager.getAllProviders();
		List<String> availableProvider = new ArrayList<String>();
		for(int i=0; i < providers.size(); i++) {
			String tempProvider = providers.get(i);
			if(locationManager.isProviderEnabled(tempProvider)) {
				availableProvider.add(tempProvider);
			}
		}
		String provider = "";
		for(int i=0; i < availableProvider.size(); i++) {
			LocationProvider locProvider = locationManager.getProvider(availableProvider.get(i));
			provider = locProvider.getName();
		}
		if(!provider.equals("")) {
			Location location = locationManager.getLastKnownLocation(provider);
			Toast toast = Toast.makeText(this, location.getLatitude()+" "+provider, 2000);
			toast.show();
			GeoPoint point = new GeoPoint((int)(location.getLatitude()*E6_MULTIPLY), (int)(location.getLongitude()*E6_MULTIPLY));
			mapController.setCenter(point);
		} else {
			Toast.makeText(this, R.string.errorToastCantFindCurrentPosition, 2000).show();
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}